﻿/*
 * Model验证
 * 注解验证框架
 */

using System.Collections;
using System.ComponentModel.DataAnnotations;

UserInfo user = new();

ValidationContext context = new(user);


ICollection<ValidationResult> errors = new List<ValidationResult>();
var valid = Validator.TryValidateObject(user, context, errors, true);

foreach (var validationResult in errors)
{
    Console.WriteLine(validationResult.ErrorMessage);
}

try
{
    Validator.ValidateObject(user, context);
}
catch (Exception e)
{
    Console.WriteLine(e.Message);
}

public class UserInfo
{
    //特性验证优先级较高
    [Required]
    public string Name { get; set; }

    [RegularExpression("\\w+@.com")]
    public string Email { get; set; }

    [StringLength(30, MinimumLength = 6)]
    public string Password { get; set; }

    [Range(18, 30)]
    public int Age { get; set; }

    public IEnumerable<ValidationResult> Validate(ValidationContext context)
    {
        if (Name == "admin" && Age < 6)
        {
            yield return new ValidationResult("管理员年龄必须大于6岁");
        }
    }
}